<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList()">
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="stateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="modifyUser(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              <el-button type="warning" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加用户信息区域 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" @close="addDialogClose()">
        <el-form
          :model="addUsers"
          :rules="addUsersRul"
          ref="addUsers"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUsers.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUsers.email"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUsers.password"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addUsers.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserTo()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息对话框 -->
      <el-dialog title="修改用户信息" :visible.sync="modifyUserShow" width="30%" @close="modifyUserClose">
        <el-form
          :model="modifyUserForm"
          :rules="modifyUserRul"
          ref="modifyUserRef"
          label-width="100px"
        >
          <el-form-item label="用户名">
            <el-input v-model="modifyUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="modifyUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="modifyUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="modifyUserShow = false">取 消</el-button>
          <el-button type="primary" @click="modifyUserTo()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 确认是否删除用户 -->
      <el-dialog title="删除用户" :visible.sync="deleteShow" width="30%">
        <span>是否删除用户？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteShow = false">取 消</el-button>
          <el-button type="primary" @click="deleteShowTo()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog title="角色分配" :visible.sync="setRoleDialogVisible" width="30%" @close="setRoleClose()">
        <div>
          <p>当前的用户：{{userInfo.username}}</p>
          <p>当前的角色：{{userInfo.role_name}}</p>
          <p>
            分配新角色：
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱
    var verifyEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法邮箱"));
    };
    // 验证手机
    var verifyPhone = (rule, value, callback) => {
      const regPhone = /^1[345678]\d{9}$/;
      if (regPhone.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法手机号"));
    };
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      modifyUserShow: false,
      deleteShow: false,
      modifyUserForm: {},
      setRoleDialogVisible: false,
      userInfo: {},
      rolesList: [],
      selectedRoleId:'',
      deleteId: "",
      addUsers: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addUsersRul: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "",
            trigger: "blur",
          },
          { validator: verifyEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            trigger: "blur",
          },
          { validator: verifyPhone, trigger: "blur" },
        ],
      },
      // 添加用户验证对象
      modifyUserRul: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "",
            trigger: "blur",
          },
          { validator: verifyEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            trigger: "blur",
          },
          { validator: verifyPhone, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用于列表失败");
      }
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 监听页面展示数量改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听页码改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 监听状态改变
    async stateChange(state) {
      const { data: res } = await this.$http.put(
        `users/${state.id}/state/${state.mg_state}`
      );
      if (res.meta.status !== 200) {
        state.mg_state = !state.mg_state;
        this.$message.error("更新用户状态失败!");
      } else {
        this.$message.success("更新用户状态成功!");
      }
    },
    // 监听dialog关闭
    addDialogClose() {
      this.$refs.addUsers.resetFields();
    },
    // 发送添加用户网络请求
    addUserTo() {
      this.$refs.addUsers.validate((valid) => {
        console.log(this.addUsers);
        if (!valid) return;
        this.$http.post("users", this.addUsers).then((res) => {
          console.log(res);
          if ((res.data.meta.status = 201)) {
            this.$message.success(res.data.meta.msg);
          } else {
            this.$message.error("添加用户失败");
          }
          this.getUserList();
        });
      });
    },
    // 修改用户信息出现
    async modifyUser(id) {
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户信息失败");
      }
      this.modifyUserForm = res.data;
      this.modifyUserShow = true;
    },
    // 发送修改用户信息请求
    modifyUserTo() {
      this.$refs.modifyUserRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "users/" + this.modifyUserForm.id,
          {
            email: this.modifyUserForm.email,
            mobile: this.modifyUserForm.mobile,
          }
        );
        if (res.meta.status !== 200) {
          this.$message.error("更新失败");
        } else {
          // 关闭窗口
          this.modifyUserShow = false;
          // 提示成功
          this.$message.success("更新成功");
          // 重新获取列表
          this.getUserList();
        }
      });
    },
    // 监听修改用户信息关闭
    modifyUserClose() {
      this.$refs.modifyUserRef.resetFields();
    },
    // 删除用户
    deleteUser(id) {
      this.deleteShow = true;
      this.deleteId = id;
    },
    // 发送删除用户请求
    async deleteShowTo() {
      const { data: res } = await this.$http.delete("users/" + this.deleteId);
      if (res.meta.status !== 200) {
        this.$message.error("删除用户失败");
      } else {
        //取消弹窗
        this.deleteShow = false;
        // 提示成功
        this.$message.success("删除用户成功");
        // 重新获取列表
        this, this.getUserList();
      }
    },
    // 展示分配角色对话框
    async setRole(userInfo) {
      this.setRoleDialogVisible = true;
      this.userInfo = userInfo;
      // 在展示对话框之前获取所有的角色列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.rolesList = res.data;
    },
    // 点击确认按钮分配橘色
    async saveRoleInfo() {
      if(!this.selectedRoleId) {
        return this.$message.error("请选择要分配的角色！")
      }
      const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{
        rid: this.selectedRoleId
      })
      if(res.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 监听分配角色关闭
    setRoleClose() {
      this.selectedRoleId = '',
      this.userInfo = ''
    }
  },
  created() {
    this.getUserList();
  },
};
</script>